package com.strelitzia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.strelitzia.dao.MessageDao;
import com.strelitzia.entity.MessageEntity;
import com.strelitzia.entity.UserEntity;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.MessageService;
import com.strelitzia.service.UserService;
import com.strelitzia.vo.MessageItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @create 2024/1/18 15:08
 */

@Service
public class MessageServiceImpl extends ServiceImpl<MessageDao, MessageEntity> implements MessageService {
    @Autowired
    private UserService userService;

    @Override
    public void add(Integer fid, String content) {
        MessageEntity messageEntity = new MessageEntity();
        messageEntity.setUid(CorsFilter.loginUserId.get());
        messageEntity.setFid(fid);
        messageEntity.setContent(content);
        messageEntity.setTime(new Timestamp(new Date().getTime()));
        this.save(messageEntity);
    }

    @Override
    public List<MessageItem> get(Integer fid) {
        List<MessageEntity> list = this.list(new QueryWrapper<MessageEntity>().eq("fid", fid).orderByAsc("time"));
        return getMessageItems(list);
    }

    @Override
    public List<MessageItem> get() {
        List<MessageEntity> list = this.list(new QueryWrapper<MessageEntity>().eq("fid", CorsFilter.loginUserId.get()).orderByAsc("time"));
        return getMessageItems(list);
    }

    private List<MessageItem> getMessageItems(List<MessageEntity> list) {
        if(list != null) {
            return list.stream().map(item -> {
                MessageItem messageItem = new MessageItem();
                messageItem.setId(item.getId());
                UserEntity byId = userService.getById(item.getUid());
                messageItem.setAvatar("/api/res/"+byId.getAvatar());
                messageItem.setContent(item.getContent());
                messageItem.setUid(item.getUid());
                return messageItem;
            }).collect(Collectors.toList());
        }else {
            return new ArrayList<>();
        }
    }
}
